package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.apis.user.IUserClient;
import com.heima.apis.wemedia.IWeMediaClient;
import com.heima.comment.service.RepayCommentService;
import com.heima.comment.util.CmtUserThreadLocalUtil;
import com.heima.common.constants.CommentConstans;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mango.dtos.CommentRepayDto;
import com.heima.model.mango.pojos.Comment;
import com.heima.model.mango.pojos.CommentRepay;
import com.heima.model.mango.pojos.LikeComment;
import com.heima.model.mango.pojos.LikeCommentRepay;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
public class RepayCommentServiceImpl implements RepayCommentService {
    @Autowired
    private IUserClient userClient;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IWeMediaClient weMediaClient;
    @Override
    public ResponseResult repaySave(CommentRepayDto dto) {
        //参数校验
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.COMMENT_NOT_EXIST);
        }
        //评论字数不能超过140
        if (dto.getContent().length()> CommentConstans.COMMENT_LIMIT){
            return ResponseResult.errorResult(AppHttpCodeEnum.COMMENT_LENTH_TOOLONG);
        }
        //内容审核
        boolean flag = commentScan(dto.getContent());
        if (!flag){
            return ResponseResult.errorResult(AppHttpCodeEnum.COMMENT_SCAN_FAIL);
        }
        CommentRepay commentRepay = new CommentRepay();
        BeanUtils.copyProperties(dto,commentRepay);
        commentRepay.setLikes(0);
        String jsonString = JSON.toJSONString(userClient.getUser(CmtUserThreadLocalUtil.getUser().getId()).getData());
        ApUser user = JSON.parseObject(jsonString, ApUser.class);
        commentRepay.setAuthorName(user.getName());
        commentRepay.setAuthorId(user.getId());
        commentRepay.setImage(user.getImage());
        commentRepay.setCreatedTime(new Date());
        mongoTemplate.save(commentRepay,"ap_repay_comment");
        Comment comment = mongoTemplate.findById(dto.getCommentId(), Comment.class, "ap_comment");
        comment.setReply(comment.getReply()+1);
        mongoTemplate.save(comment,"ap_comment");
        log.info("存入mongodb");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult loadRepay(CommentRepayDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        Query query = Query.query(Criteria
                        .where("commentId")
                        .is(dto.getCommentId())
                        .and("createdTime")
                        .lt(dto.getMinDate()))
//                    .limit(dto.getSize())
                .with(sort);
        List<CommentRepay> repayComments = mongoTemplate.find(query, CommentRepay.class, "ap_repay_comment");
        for (CommentRepay repayComment : repayComments) {
            Query query1 = Query.query(Criteria.where("commentRepayId").is(repayComment.getId()).and("likerId").is(CmtUserThreadLocalUtil.getUser().getId()));
            LikeCommentRepay likeCommentRepay = mongoTemplate.findOne(query1, LikeCommentRepay.class, "ap_like_comment_repay");
            if (likeCommentRepay!=null){
                repayComment.setOperation((short) 0);
            }else repayComment.setOperation(null);
        }
        return ResponseResult.okResult(repayComments);
    }

    @Override
    public ResponseResult likeRepay(CommentRepayDto dto) {
        if (dto == null || dto.getOperation() ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        CommentRepay comment = mongoTemplate.findById(dto.getCommentRepayId(), CommentRepay.class, "ap_repay_comment");
        if (dto.getOperation()==CommentConstans.COMMENT_LIKE){
            comment.setOperation(dto.getOperation());
            comment.setLikes(comment.getLikes()+1);
            mongoTemplate.save(comment, "ap_repay_comment");
            LikeCommentRepay likeCommentRepay = new LikeCommentRepay();
            likeCommentRepay.setLikerId(CmtUserThreadLocalUtil.getUser().getId());
            likeCommentRepay.setCommentRepayId(comment.getId());
            likeCommentRepay.setCreatTime(new Date());
            mongoTemplate.save(likeCommentRepay,"ap_like_comment_repay");
            return ResponseResult.okResult(comment.getLikes());
        }else if ( CommentConstans.COMMENT_CANCLELIKE.equals(dto.getOperation())){
            comment.setOperation(null);
            comment.setLikes(comment.getLikes()-1);
            mongoTemplate.save(comment,"ap_repay_comment");
            //删除关联表的内容
            Query query = Query.query(Criteria.where("commentRepayId").is(comment.getId()).and("authorId").is(CmtUserThreadLocalUtil.getUser().getId()));
            mongoTemplate.remove(query, LikeCommentRepay.class,"ap_like_comment_repay");
            return ResponseResult.okResult(comment.getLikes());
        }
        else throw new RuntimeException("当前没有点赞不能取消点赞，或参数有误");
    }


    private boolean commentScan(String comment) {
        boolean flag=true;
        ResponseResult responseResult = weMediaClient.commentScan();
        String json = JSONArray.toJSONString(responseResult.getData());//JSON转换，用（LIST）强转则会变成LinkHashMap
        List<WmSensitive> wmSensitives = JSON.parseArray(json,WmSensitive.class);
        if(CollectionUtils.isEmpty(wmSensitives)){
            return flag;
        }
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        SensitiveWordUtil.initMap(sensitiveList);
        Map<String, Integer> reslutMap = SensitiveWordUtil.matchWords(comment);
        log.info("敏感词审核结果：{}",reslutMap);
        if(reslutMap.size() > 0){
            flag = false;
        }
        return flag;
    }
}
